package com.agrimall.servlet.client;

import com.agrimall.entity.Order;
import com.agrimall.entity.Review;
import com.agrimall.entity.User;
import com.agrimall.service.OrderService;
import com.agrimall.service.ReviewService;
import com.agrimall.service.impl.OrderServiceImpl;
import com.agrimall.service.impl.ReviewServiceImpl;
import com.agrimall.util.FileUploadUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 客户端评价管理Servlet
 */
@WebServlet("/client/review")
public class ReviewServlet extends HttpServlet {
    private ReviewService reviewService = new ReviewServiceImpl();
    private OrderService orderService = new OrderServiceImpl();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        
        if (user == null) {
            response.sendRedirect(request.getContextPath() + "/login.jsp");
            return;
        }
        
        String action = request.getParameter("action");
        
        if (action == null || action.equals("") || action.equals("list")) {
            // 评价列表
            listReviews(request, response, user);
        } else if (action.equals("add")) {
            // 添加评价页面
            addReviewPage(request, response, user);
        } else if (action.equals("delete")) {
            // 删除评价
            deleteReview(request, response, user);
        } else {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        
        if (user == null) {
            response.sendRedirect(request.getContextPath() + "/login.jsp");
            return;
        }
        
        String action = request.getParameter("action");
        
        if (action != null && action.equals("add")) {
            // 添加评价（表单提交）
            addReview(request, response, user);
        } else if (action != null && action.equals("addAjax")) {
            // 添加评价（AJAX，支持文件上传）
            addReviewAjax(request, response, user);
        } else {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }
    
    /**
     * 评价列表
     */
    private void listReviews(HttpServletRequest request, HttpServletResponse response, User user)
            throws ServletException, IOException {
        try {
            String pageStr = request.getParameter("page");
            int page = 1;
            if (pageStr != null && !pageStr.isEmpty()) {
                try {
                    page = Integer.parseInt(pageStr);
                } catch (NumberFormatException e) {
                    page = 1;
                }
            }
            int pageSize = 10;
            
            List<Review> reviews = reviewService.getReviewListByUser(user.getUserId(), page, pageSize);
            if (reviews == null) {
                reviews = new java.util.ArrayList<>();
            }
            
            int totalCount = reviewService.countReviewsByUser(user.getUserId());
            
            int totalPages = (int) Math.ceil((double) totalCount / pageSize);
            if (totalPages == 0) {
                totalPages = 1;
            }
            
            boolean hasNextPage = page < totalPages;
            
            request.setAttribute("reviews", reviews);
            request.setAttribute("page", page);
            request.setAttribute("totalCount", totalCount);
            request.setAttribute("totalPages", totalPages);
            request.setAttribute("hasNextPage", hasNextPage);
            request.getRequestDispatcher("/client/review/list.jsp").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "查询评价失败：" + e.getMessage());
            request.getRequestDispatcher("/client/review/list.jsp").forward(request, response);
        }
    }
    
    /**
     * 添加评价页面
     */
    private void addReviewPage(HttpServletRequest request, HttpServletResponse response, User user)
            throws ServletException, IOException {
        String orderIdStr = request.getParameter("orderId");
        if (orderIdStr == null) {
            response.sendRedirect(request.getContextPath() + "/client/order?action=list");
            return;
        }
        
        try {
            Long orderId = Long.parseLong(orderIdStr);
            Order order = orderService.getOrderById(orderId);
            
            if (order == null || !order.getUserId().equals(user.getUserId())) {
                response.sendRedirect(request.getContextPath() + "/client/order?action=list");
                return;
            }
            
            Review existingReview = reviewService.getReviewByOrderId(orderId);
            if (existingReview != null) {
                request.setAttribute("message", "该订单已评价");
                request.setAttribute("review", existingReview);
            }
            
            request.setAttribute("order", order);
            request.getRequestDispatcher("/client/review/add.jsp").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
            response.sendRedirect(request.getContextPath() + "/client/order?action=list");
        }
    }
    
    /**
     * 添加评价（表单提交）
     */
    private void addReview(HttpServletRequest request, HttpServletResponse response, User user)
            throws ServletException, IOException {
        try {
            String orderIdStr = request.getParameter("orderId");
            String productIdStr = request.getParameter("productId");
            String ratingStr = request.getParameter("rating");
            String content = request.getParameter("content");
            String images = request.getParameter("images");
            
            if (orderIdStr == null || productIdStr == null || ratingStr == null) {
                request.setAttribute("error", "参数不完整");
                request.getRequestDispatcher("/client/review/add.jsp").forward(request, response);
                return;
            }
            
            Review review = new Review();
            review.setOrderId(Long.parseLong(orderIdStr));
            review.setProductId(Long.parseLong(productIdStr));
            review.setUserId(user.getUserId());
            review.setRating(Integer.parseInt(ratingStr));
            review.setContent(content);
            review.setImages(images);
            
            boolean success = reviewService.addReview(review);
            if (success) {
                response.sendRedirect(request.getContextPath() + "/client/review?action=list");
            } else {
                request.setAttribute("error", "评价失败，请重试");
                request.getRequestDispatcher("/client/review/add.jsp").forward(request, response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "评价失败：" + e.getMessage());
            request.getRequestDispatcher("/client/review/add.jsp").forward(request, response);
        }
    }
    
    /**
     * 添加评价（AJAX，支持文件上传）
     */
    private void addReviewAjax(HttpServletRequest request, HttpServletResponse response, User user)
            throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        try {
            String orderIdStr = null;
            String productIdStr = null;
            String ratingStr = null;
            String content = null;
            String images = null;
            
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
            
            if (isMultipart) {
                FileItemFactory factory = new DiskFileItemFactory();
                ServletFileUpload upload = new ServletFileUpload(factory);
                upload.setSizeMax(5 * 1024 * 1024 * 3);
                
                List<FileItem> items = upload.parseRequest(request);
                
                try {
                    images = FileUploadUtil.uploadImages(items, request, 3);
                } catch (Exception e) {
                    out.print("{\"success\":false,\"message\":\"图片上传失败：" + e.getMessage() + "\"}");
                    return;
                }
                
                for (FileItem item : items) {
                    if (item.isFormField()) {
                        String fieldName = item.getFieldName();
                        String fieldValue = item.getString("UTF-8");
                        
                        if ("orderId".equals(fieldName)) {
                            orderIdStr = fieldValue;
                        } else if ("productId".equals(fieldName)) {
                            productIdStr = fieldValue;
                        } else if ("rating".equals(fieldName)) {
                            ratingStr = fieldValue;
                        } else if ("content".equals(fieldName)) {
                            content = fieldValue;
                        }
                    }
                }
            } else {
                orderIdStr = request.getParameter("orderId");
                productIdStr = request.getParameter("productId");
                ratingStr = request.getParameter("rating");
                content = request.getParameter("content");
                images = request.getParameter("images");
            }
            
            if (orderIdStr == null || productIdStr == null || ratingStr == null) {
                out.print("{\"success\":false,\"message\":\"参数不完整\"}");
                return;
            }
            
            if (content == null || content.trim().isEmpty()) {
                out.print("{\"success\":false,\"message\":\"请输入评价内容\"}");
                return;
            }
            
            Review review = new Review();
            review.setOrderId(Long.parseLong(orderIdStr));
            review.setProductId(Long.parseLong(productIdStr));
            review.setUserId(user.getUserId());
            review.setRating(Integer.parseInt(ratingStr));
            review.setContent(content.trim());
            if (images != null && !images.trim().isEmpty()) {
                review.setImages(images.trim());
            }
            
            boolean success = reviewService.addReview(review);
            if (success) {
                out.print("{\"success\":true,\"message\":\"评价成功\"}");
            } else {
                if (images != null && !images.trim().isEmpty()) {
                    FileUploadUtil.deleteFiles(request, images);
                }
                out.print("{\"success\":false,\"message\":\"评价失败，请重试\"}");
            }
        } catch (NumberFormatException e) {
            out.print("{\"success\":false,\"message\":\"参数格式错误\"}");
        } catch (Exception e) {
            e.printStackTrace();
            out.print("{\"success\":false,\"message\":\"服务器错误：" + e.getMessage() + "\"}");
        } finally {
            out.flush();
            out.close();
        }
    }
    
    /**
     * 删除评价
     */
    private void deleteReview(HttpServletRequest request, HttpServletResponse response, User user)
            throws ServletException, IOException {
        response.setCharacterEncoding("UTF-8");
        
            String reviewIdStr = request.getParameter("reviewId");
        if (reviewIdStr == null) {
            String error = URLEncoder.encode("参数错误", StandardCharsets.UTF_8.toString());
            response.sendRedirect(request.getContextPath() + "/client/review?action=list&error=" + error);
            return;
        }
        
        try {
            Long reviewId = Long.parseLong(reviewIdStr);
            boolean success = reviewService.deleteReview(reviewId, user.getUserId());
            
            if (success) {
                String message = URLEncoder.encode("删除成功", StandardCharsets.UTF_8.toString());
                response.sendRedirect(request.getContextPath() + "/client/review?action=list&message=" + message);
            } else {
                String error = URLEncoder.encode("删除失败，可能是评价不存在或无权删除", StandardCharsets.UTF_8.toString());
                response.sendRedirect(request.getContextPath() + "/client/review?action=list&error=" + error);
            }
        } catch (NumberFormatException e) {
            String error = URLEncoder.encode("参数错误", StandardCharsets.UTF_8.toString());
            response.sendRedirect(request.getContextPath() + "/client/review?action=list&error=" + error);
        } catch (Exception e) {
            e.printStackTrace();
            String error = URLEncoder.encode("删除失败：" + e.getMessage(), StandardCharsets.UTF_8.toString());
            response.sendRedirect(request.getContextPath() + "/client/review?action=list&error=" + error);
        }
    }
}

